<template>
  <div class="fill">
    <el-table :data="paperJudgeInfo.arr" border v-loading="loading">
      <el-table-column prop="id" label="题目编号" width="100"></el-table-column>
      <el-table-column prop="subject" label="所属科目" width="100"></el-table-column>
      <el-table-column prop="question" label="题目" width="180"></el-table-column>
      <el-table-column prop="score" label="分数" width="120"></el-table-column>
      <el-table-column prop="answer" label="正确答案" width="150"></el-table-column>
      <el-table-column prop="analysis" label="题目解析" width="500"></el-table-column>
      <el-table-column fixed="right" label="操作" width="300">
        <template #default="scope">
          <el-button @click="editJudge(scope.$index,scope.row)" type="primary" size="small">修改试题</el-button>
          <el-button @click="addPaperJudge(scope.row.id)" type="success" size="small">添加到题库</el-button>
          <el-button @click="deleteJudge(scope.row.id)" type="danger" size="small">删除试题</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-config-provider :locale="zhCn">
      <el-pagination
          @size-change="pageSizeChange"
          @current-change="pageNumChange"
          :current-page="pagination.pageNum"
          :page-sizes="[3, 6, 9, 12]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total">
      </el-pagination>
    </el-config-provider>
    <el-dialog
        title="编辑试卷信息"
        v-model="dialogVisibleEdit"
        width="30%"
        :before-close="handleCloseEdit">
      <section class="update">
        <el-form ref="changJudgeRef" :model="paperJudgeInfo.edit" label-width="80px">
          <el-form-item label="题库编号">
            <el-input v-model="paperJudgeInfo.edit.id" disabled></el-input>
          </el-form-item>
          <el-form-item label="所属科目">
            <el-input v-model="paperJudgeInfo.edit.subject"></el-input>
          </el-form-item>
          <el-space fill>
            <el-alert type="info" show-icon :closable="false">
              <p>判断题分数为空或者不设置默认为 2分</p>
            </el-alert>
            <el-form-item label="分数"
                          prop="score"
                          :rules="[{validator: checkNumber, trigger: 'change'}]">
              <el-input v-model="paperJudgeInfo.edit.score"></el-input>
            </el-form-item>
          </el-space>
          <el-form-item label="题目">
            <el-input type="textarea" v-model="paperJudgeInfo.edit.question"></el-input>
          </el-form-item>
          <el-space fill>
            <el-alert type="info" show-icon :closable="false">
              <p>判断题答案T代表正确，F代表错误</p>
            </el-alert>
            <el-radio-group v-model="questionInfo.judgeQuestion.answer">
              <el-radio label="T">正确</el-radio>
              <el-radio label="F">错误</el-radio>
            </el-radio-group>
          </el-space>
          <el-form-item label="题目解析">
            <el-input type="textarea" v-model="paperJudgeInfo.edit.analysis"></el-input>
          </el-form-item>
        </el-form>
      </section>
      <template v-slot:footer>
        <el-button @click="editBack()">取 消</el-button>
        <el-button type="primary" @click="editSubmit()">确 定</el-button>
      </template>
    </el-dialog>
    <el-dialog
        title="添加到题库"
        v-model="dialogVisibleAdd"
        width="30%"
        :before-close="handleCloseAdd">
      <el-form ref="addJudgePaperRef" :model="paperJudgeInfo.addPaperMap" label-width="80px">
        <el-form-item label="添加题库"
                      prop="paperId"
                      :rules="[{required: true, message: '请选择题库', trigger: 'change'}]">
          <el-select v-model="paperJudgeInfo.addPaperMap.paperId" class="m-2" placeholder="请选择题库">
            <el-option
                v-for="(item,index) in paperJudgeInfo.paper"
                :key="index"
                :label="item.id +': '+item.paperName"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <el-button @click="addBack()">取 消</el-button>
        <el-button type="primary" @click="addSubmit()">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {getCurrentInstance, onMounted, reactive, ref} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {isObjectValueEqual} from "@/utils/funUtils";
import AES from "@/utils/AESUtil";
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
export default {
  name: "judgeAnswer",
  setup(){
    const {proxy} = getCurrentInstance()
    // eslint-disable-next-line no-undef
    const role = ref(AES.Decrypt($cookies.get("role")))
    let changJudgeRef = ref(null)
    let addJudgePaperRef = ref(null)
    let dialogVisibleEdit = ref(false)
    let dialogVisibleAdd = ref(false)
    let loading = ref(false) //加载标识符
    let paperJudgeInfo = reactive({
      arr: [],
      edit: {},
      editIndex: null,
      addPaperMap: {
        paperId: null,
        questionType: 3,
        questionId: null
      },
      paper: []
    })
    let pagination = reactive({
      pageNum: 1, //当前页
      total: Number(''), //记录条数
      pageSize: 5 //每页条数
    })
    let checkQuestion = (rule,value,callback) => {
      if (value.includes('（）')) {
        callback(new Error('请输入英文括号'))
      }else {
        callback()
      }
    }
    let checkAnswer = (rule,value,callback) => {
      if (value.includes('，')) {
        callback(new Error('请输入英文逗号'))
      }else {
        callback()
      }
    }
    let checkNumber = (rule,value,callback) => {
      const boolean = new RegExp('^[1-9][0-9]*$').test(value)
      if (!boolean) {
        callback(new Error('请输入正整数'))
      }else {
        callback()
      }
    }
    onMounted(()=>{
      getJudgeInfo()
    })
    function getJudgeInfo(){
      loading.value = true
      if (role.value === '1') {
        proxy.$axios.get(
            // eslint-disable-next-line no-undef
            `/manage/judge/${$cookies.get('id')}/${pagination.pageNum}/${pagination.pageSize}`
        ).then(
            response => {
              paperJudgeInfo.arr = [...response.data.list]
              pagination.total = response.data.total
              pagination.pageNum = response.data.pageNum
              pagination.pageSize = response.data.pageSize
              loading.value = false
            },
            error => {
              console.log('请求失败', error.message)
            }
        )
        proxy.$axios.get(
            // eslint-disable-next-line no-undef
            `/manage/mypaper/${$cookies.get('id')}`
        ).then(
            response => {
              paperJudgeInfo.paper = response.data
            },
            error => {
              console.log('请求失败', error.message)
            }
        )
      }else if (role.value === '0'){
        proxy.$axios.get(
            // eslint-disable-next-line no-undef
            `/manage/judge/${pagination.pageNum}/${pagination.pageSize}`
        ).then(
            response => {
              paperJudgeInfo.arr = [...response.data.list]
              pagination.total = response.data.total
              pagination.pageNum = response.data.pageNum
              pagination.pageSize = response.data.pageSize
              loading.value = false
            },
            error => {
              console.log('请求失败', error.message)
            }
        )
        proxy.$axios.get(
            `/manage/paper`
        ).then(
            response => {
              paperJudgeInfo.paper = response.data
            },
            error => {
              console.log('请求失败', error.message)
            }
        )
      }
    }
    function pageSizeChange(value){//改变当前记录条数
      pagination.pageSize = value
      getJudgeInfo()
    }
    function pageNumChange(value){//改变当前页码
      pagination.pageNum = value
      getJudgeInfo()
    }
    function handleCloseEdit(done){
      ElMessageBox.confirm('确认关闭？',"",
          {
            confirmButtonText: '是',
            cancelButtonText: '否',
            type: 'warning',
          }
      ).then(() => {
        done();
        ElMessage({
          type: 'info',
          message: '取消修改',
        })
      }).catch(() => {});
    }

    function editJudge(index,value){
      dialogVisibleEdit.value = true
      paperJudgeInfo.editIndex = index
      paperJudgeInfo.edit = {...value}
    }
    function editSubmit(){
      proxy.$refs.changJudgeRef.validate((valid) => {
        if (valid) {
          if (isObjectValueEqual(paperJudgeInfo.arr[paperJudgeInfo.editIndex],paperJudgeInfo.edit)){
            ElMessage({
              type: 'info',
              message: '信息没有改动',
            })
            return false
          }
          proxy.$axios.put(
              `/manage/judge/update`,
              {...paperJudgeInfo.edit}
          ).then(
              response => {
                if (response.data) {
                  ElMessage({
                    type: 'success',
                    message: '修改成功',
                  })
                  dialogVisibleEdit.value = false
                  getJudgeInfo()
                }
              },
              error => {
                console.log('请求失败', error.message)
              }
          )
        }else {
          return false
        }
      })

    }
    function editBack(){
      dialogVisibleEdit.value = false
      ElMessage({
        type: 'info',
        message: '取消修改',
      })
      proxy.$refs.changJudgeRef.clearValidate()
    }
    function deleteJudge(id) {
      ElMessageBox.confirm(
          '是否永久删除该考试信息,该操作不可逆！！！',
          '警告',
          {
            confirmButtonText: '是',
            cancelButtonText: '否',
            type: 'warning',
          }
      ).then(() => {
        proxy.$axios.delete(`/manage/judge/delete/${id}`).then(
            response => {
              if (response.data){
                ElMessage({
                  type: 'success',
                  message: '删除成功',
                })
                getJudgeInfo()
              }else {
                ElMessage({
                  type: 'error',
                  message: '删除失败，请联系管理员',
                })
              }
            },
            error => {
              console.log('请求失败', error.message)
            }
        )
      }).catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
    }
    function addPaperJudge(id){
      dialogVisibleAdd.value = true
      paperJudgeInfo.addPaperMap.questionId = id
    }
    function addBack(){
      dialogVisibleAdd.value = false
      ElMessage({
        type: 'info',
        message: '取消添加',
      })
      proxy.$refs.addJudgePaperRef.clearValidate()
    }
    function addSubmit() {
      proxy.$refs.addJudgePaperRef.validate((valid) => {
        if (valid) {
          proxy.$axios.post(
              `/manage/paper/map/add`,
              {...paperJudgeInfo.addPaperMap}
          ).then(
              response => {
                if (response.data) {
                  ElMessage({
                    type: 'success',
                    message: '添加成功',
                  })
                  dialogVisibleAdd.value = false
                  getJudgeInfo()
                }
              },
              error => {
                console.log('请求失败', error.message)
              }
          )
        } else {
          return false
        }
      })
    }
    function handleCloseAdd(done){
      ElMessageBox.confirm('确认关闭？',"",
          {
            confirmButtonText: '是',
            cancelButtonText: '否',
            type: 'warning',
          }
      ).then(() => {
        done();
        proxy.$refs.addChoicePaperRef.resetFields()
        ElMessage({
          type: 'info',
          message: '取消添加',
        })
      }).catch(() => {});
    }
    return{
      changJudgeRef,
      addJudgePaperRef,
      paperJudgeInfo,
      pagination,
      loading,
      dialogVisibleEdit,
      dialogVisibleAdd,
      pageSizeChange,
      pageNumChange,
      handleCloseEdit,
      editJudge,
      editSubmit,
      editBack,
      deleteJudge,
      checkQuestion,
      checkAnswer,
      checkNumber,
      addPaperJudge,
      addBack,
      addSubmit,
      handleCloseAdd,
      zhCn
    }
  }
}
</script>

<style scoped>
.fill {
  padding: 0px 40px;
}
.fill .page {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.fill .edit{
  margin-left: 20px;
}
</style>